<script setup lang="ts">
import MarkdownIt from 'markdown-it';

definePageMeta({ layout: 'default' });

const route = useRoute();
const id = computed(() => parseInt(route.params.id as string));

const article = ref<any>(null);
const title = ref('');
const content = ref('');
const status = ref<'draft' | 'published'>('draft');
const shareUrl = ref('');
const loading = ref(true);
const saving = ref(false);
const dirty = ref(false);

const md = new MarkdownIt({ html: false, linkify: true, breaks: true });
const previewHtml = computed(() => md.render(content.value));

let saveTimer: ReturnType<typeof setTimeout> | null = null;

async function fetchArticle() {
  loading.value = true;
  const res = await $fetch<any>(`/api/articles/${id.value}`);
  if (res.code === 0) {
    article.value = res.data;
    title.value = res.data.title || '';
    content.value = res.data.content || '';
    status.value = res.data.status || 'draft';
  }
  loading.value = false;
}

function onContentChange() {
  dirty.value = true;
  if (saveTimer) clearTimeout(saveTimer);
  saveTimer = setTimeout(saveArticle, 2000);
}

async function saveArticle() {
  if (!dirty.value) return;
  saving.value = true;
  await $fetch(`/api/articles/${id.value}`, {
    method: 'PATCH',
    body: { title: title.value, content: content.value, status: status.value },
  });
  dirty.value = false;
  saving.value = false;
}

async function toggleStatus() {
  status.value = status.value === 'draft' ? 'published' : 'draft';
  dirty.value = true;
  await saveArticle();
}

async function doShare() {
  const res = await $fetch<any>(`/api/articles/${id.value}/share`, { method: 'POST' });
  if (res.code === 0) {
    shareUrl.value = window.location.origin + res.data.url;
    navigator.clipboard?.writeText(shareUrl.value);
  }
}

function copyShareLink() {
  if (shareUrl.value) navigator.clipboard?.writeText(shareUrl.value);
}

onMounted(fetchArticle);
onUnmounted(() => {
  if (saveTimer) clearTimeout(saveTimer);
  if (dirty.value) saveArticle();
});
</script>

<template>
  <div class="editor-page">
    <!-- Top Bar -->
    <div class="editor-topbar">
      <div class="topbar-left">
        <button class="btn-back" @click="navigateTo('/articles')">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg>
          返回
        </button>
        <input
          v-model="title"
          class="title-input"
          placeholder="文章标题"
          @input="onContentChange"
        />
      </div>
      <div class="topbar-right">
        <span class="save-indicator" :class="{ saved: !dirty && !saving }">
          {{ saving ? '保存中...' : dirty ? '未保存' : '已保存' }}
        </span>
        <button class="btn-status" :class="status" @click="toggleStatus">
          {{ status === 'published' ? '已发布' : '草稿' }}
        </button>
        <button class="btn-share" @click="doShare">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
          分享
        </button>
        <button class="btn-save" @click="saveArticle">保存</button>
      </div>
    </div>

    <!-- Share Modal -->
    <div v-if="shareUrl" class="share-overlay" @click.self="shareUrl = ''">
      <div class="share-card">
        <div class="share-title">分享链接已生成</div>
        <div class="share-url">{{ shareUrl }}</div>
        <button class="btn-copy" @click="copyShareLink">复制链接</button>
        <button class="btn-close-share" @click="shareUrl = ''">关闭</button>
      </div>
    </div>

    <div v-if="loading" class="empty-state">
      <div class="empty-state-icon">⏳</div>
      <div>加载中...</div>
    </div>

    <div v-else class="editor-body">
      <!-- Editor Panel -->
      <div class="editor-panel">
        <textarea
          v-model="content"
          class="editor-textarea"
          placeholder="开始写作 Markdown..."
          @input="onContentChange"
        />
      </div>

      <!-- Preview Panel -->
      <div class="preview-panel">
        <div class="preview-content" v-html="previewHtml" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.editor-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg);
}
.editor-topbar {
  height: 48px;
  background: var(--bg2);
  border-bottom: 1px solid var(--border);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  flex-shrink: 0;
  gap: 12px;
}
.topbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
}
.topbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}
.btn-back {
  background: none;
  border: none;
  color: var(--text2);
  cursor: pointer;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: color 0.15s;
  flex-shrink: 0;
}
.btn-back:hover { color: var(--text); }
.title-input {
  flex: 1;
  background: transparent;
  border: none;
  color: var(--text);
  font-family: var(--font-display);
  font-size: 16px;
  outline: none;
  min-width: 0;
}
.title-input::placeholder { color: var(--text3); }
.save-indicator { font-size: 11px; color: var(--text3); }
.save-indicator.saved { color: var(--success); }
.btn-status {
  background: var(--bg3);
  border: 1px solid var(--border);
  color: var(--text2);
  padding: 5px 10px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.15s;
}
.btn-status.published { color: var(--success); border-color: rgba(93,184,114,0.3); }
.btn-share {
  background: var(--bg3);
  border: 1px solid var(--border);
  color: var(--text2);
  padding: 5px 10px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.15s;
}
.btn-share:hover { color: var(--text); }
.btn-save {
  background: var(--accent);
  color: #1a1208;
  border: none;
  padding: 6px 14px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.15s;
}
.btn-save:hover { background: #d4b88a; }

.share-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}
.share-card {
  background: var(--bg2);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  max-width: 420px;
  width: 90%;
}
.share-title {
  font-family: var(--font-display);
  font-size: 18px;
  margin-bottom: 12px;
}
.share-url {
  font-family: var(--font-mono);
  font-size: 12px;
  padding: 8px 12px;
  background: var(--bg3);
  border-radius: 6px;
  color: var(--text2);
  word-break: break-all;
  margin-bottom: 16px;
}
.btn-copy {
  background: var(--accent);
  color: #1a1208;
  border: none;
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  margin-right: 8px;
}
.btn-close-share {
  background: var(--bg3);
  border: 1px solid var(--border);
  color: var(--text2);
  padding: 8px 20px;
  border-radius: 6px;
  font-size: 13px;
  cursor: pointer;
}

.editor-body {
  flex: 1;
  display: flex;
  overflow: hidden;
}
.editor-panel {
  flex: 1;
  overflow: hidden;
}
.editor-textarea {
  width: 100%;
  height: 100%;
  background: var(--bg);
  border: none;
  border-right: 1px solid var(--border);
  color: var(--text);
  font-family: var(--font-mono);
  font-size: 14px;
  line-height: 1.7;
  padding: 20px;
  resize: none;
  outline: none;
}
.editor-textarea::placeholder { color: var(--text3); }
.preview-panel {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: var(--bg);
}
.preview-content :deep(h1) {
  font-family: var(--font-display);
  font-size: 24px;
  font-weight: 500;
  margin: 0 0 12px;
}
.preview-content :deep(h2) {
  font-family: var(--font-display);
  font-size: 20px;
  font-weight: 500;
  margin: 24px 0 10px;
}
.preview-content :deep(h3) {
  font-family: var(--font-display);
  font-size: 17px;
  font-weight: 500;
  margin: 20px 0 8px;
}
.preview-content :deep(p) { margin: 0 0 10px; line-height: 1.7; }
.preview-content :deep(code) {
  background: var(--bg3);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: var(--font-mono);
  font-size: 13px;
}
.preview-content :deep(pre) {
  background: var(--bg2);
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 14px;
  overflow-x: auto;
}
.preview-content :deep(pre code) { background: none; padding: 0; }
.preview-content :deep(blockquote) {
  border-left: 3px solid var(--accent);
  padding: 4px 0 4px 14px;
  margin: 10px 0;
  color: var(--text2);
  font-style: italic;
}
.preview-content :deep(ul), .preview-content :deep(ol) { padding-left: 20px; margin: 8px 0; }
.preview-content :deep(li) { margin: 4px 0; line-height: 1.6; }
.preview-content :deep(a) { color: var(--accent); }
.preview-content :deep(img) { max-width: 100%; border-radius: 8px; }
.preview-content :deep(hr) {
  border: none;
  border-top: 1px solid var(--border);
  margin: 20px 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  gap: 12px;
  color: var(--text3);
}
.empty-state-icon { font-size: 40px; opacity: 0.5; }
</style>
